import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intl/intl.dart';
import 'package:my_salary/pages/drawer_menu.dart';
import 'package:my_salary/pages/home/home_vm.dart';
import 'package:my_salary/route/route_utils.dart';

class HomePageBckup extends StatefulWidget {
  const HomePageBckup({super.key});

  @override
  State<StatefulWidget> createState() => _HomePageBckupState();
}

class _HomePageBckupState extends State<HomePageBckup> with WidgetsBindingObserver {
  final HomeViewModel _viewModel = HomeViewModel();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  Widget build(BuildContext context) {
    double spentPercentage =
        (_viewModel.totalExpenses / _viewModel.budget).clamp(0.0, 1.0);

    // 获取屏幕信息
    final mediaQuery = MediaQuery.of(context);
    final isLandscape = mediaQuery.orientation == Orientation.landscape;
    final maxContentWidth = isLandscape ? 600.w : double.infinity;

    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Home',
          style: Theme.of(context).textTheme.titleLarge,
        ),
        backgroundColor: Theme.of(context).colorScheme.surface,
        elevation: 0.5,
      ),
      drawer: const DrawerMenu(),
      backgroundColor: Theme.of(context).colorScheme.surface,
      body: SafeArea(
        child: ConstrainedBox(
          constraints: BoxConstraints(maxWidth: maxContentWidth),
          child: SingleChildScrollView(
            padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 8.h),
            child: Column(
              children: [
                _buildBalanceCard(isLandscape, spentPercentage),
                SizedBox(height: 12.h),
                _buildRecentExpensesHeader(),
                SizedBox(height: 8.h),
                _buildExpensesList(isLandscape, mediaQuery),
              ],
            ),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Theme.of(context).colorScheme.onPrimary,
        onPressed: _showAddExpenseDialog,
        elevation: 2,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget _buildBalanceCard(isLandscape, spentPercentage) {
    return Container(
      margin: EdgeInsets.all(isLandscape ? 10.w : 10.h),
      padding: EdgeInsets.all(isLandscape ? 12.w : 12.h),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Theme.of(context).colorScheme.primary.withOpacity(0.85),
            Theme.of(context).colorScheme.primaryContainer.withOpacity(0.95),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(20.r),
        boxShadow: [
          BoxShadow(
            color: Theme.of(context).colorScheme.primary.withOpacity(0.25),
            blurRadius: 10.r,
            offset: const Offset(0, 5),
          )
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 顶部标题 + 编辑按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                "Total Balance",
                style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                      color: Colors.white70,
                      fontSize: 16.sp,
                    ),
              ),
              IconButton(
                onPressed: _showBudgetDialog,
                icon: const Icon(Icons.edit, color: Colors.white),
                tooltip: 'Edit Budget',
              ),
            ],
          ),
          SizedBox(height: 8.h),

          // 总余额
          Text(
            "\$${_viewModel.totalBalance.toStringAsFixed(2)}",
            style: Theme.of(context).textTheme.titleLarge?.copyWith(
                  fontSize: 32.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
          ),
          SizedBox(height: 20.h),

          // 预算与百分比
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                "Budget: \$${_viewModel.budget.toStringAsFixed(2)}",
                style: Theme.of(context).textTheme.bodySmall?.copyWith(
                      color: Colors.white70,
                    ),
              ),
              Text(
                "${(spentPercentage * 100).toStringAsFixed(1)}% Spent",
                style: Theme.of(context).textTheme.bodySmall?.copyWith(
                      color: Colors.white70,
                    ),
              ),
            ],
          ),
          SizedBox(height: 8.h),

          // 进度条
          ClipRRect(
            borderRadius: BorderRadius.circular(10.r),
            child: LinearProgressIndicator(
              value: spentPercentage,
              backgroundColor: Colors.white.withOpacity(0.2),
              valueColor: AlwaysStoppedAnimation<Color>(
                spentPercentage > 0.9
                    ? Colors.redAccent
                    : spentPercentage > 0.7
                        ? Colors.orange
                        : Colors.greenAccent,
              ),
              minHeight: 8.h,
            ),
          ),
          SizedBox(height: 12.h),

          // Budget / Expenses
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Icon(Icons.arrow_upward,
                      color: Colors.greenAccent, size: 18.sp),
                  SizedBox(width: 4.w),
                  Text("Budget",
                      style: TextStyle(fontSize: 12.sp, color: Colors.white)),
                  SizedBox(width: 4.w),
                  Text(
                    "\$${_viewModel.budget.toStringAsFixed(2)}",
                    style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.bold),
                  )
                ],
              ),
              Row(
                children: [
                  Icon(Icons.arrow_downward,
                      color: Colors.redAccent, size: 18.sp),
                  SizedBox(width: 4.w),
                  Text("Expenses",
                      style: TextStyle(fontSize: 12.sp, color: Colors.white)),
                  SizedBox(width: 4.w),
                  Text(
                    "\$${_viewModel.totalExpenses.toStringAsFixed(2)}",
                    style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.bold),
                  )
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildRecentExpensesHeader() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 4.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            "Recent Transactions",
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Theme.of(context).colorScheme.onSurface,
                ),
          ),
          TextButton(
            onPressed: () {},
            style: TextButton.styleFrom(
              padding: EdgeInsets.zero,
              minimumSize: Size(40.w, 30.h),
              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
            ),
            child: Text("More", style: Theme.of(context).textTheme.bodyMedium),
          ),
        ],
      ),
    );
  }

  Widget _buildExpensesList(isLandscape, MediaQueryData mediaQuery) {
    return Container(
      height: isLandscape
          ? mediaQuery.size.height * 0.5.h
          : mediaQuery.size.height * 0.4.h,
      child: _viewModel.recentExpenses.isEmpty
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.receipt_long_outlined,
                    color: Theme.of(context).colorScheme.onSurfaceVariant,
                    size: 50.sp,
                  ),
                  SizedBox(height: 16.h),
                  Text(
                    "No Expenses yet",
                    style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                          fontSize: 16.sp,
                          color: Theme.of(context).colorScheme.onSurfaceVariant,
                        ),
                  ),
                ],
              ),
            )
          : ListView.builder(
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              itemCount: _viewModel.recentExpenses.length,
              itemBuilder: (BuildContext context, int index) {
                final expense = _viewModel.recentExpenses[
                    _viewModel.recentExpenses.length - 1 - index];
                return Dismissible(
                  key: Key(expense.id),
                  direction: DismissDirection.endToStart,
                  background: Container(
                    alignment: Alignment.centerRight,
                    padding: EdgeInsets.only(right: 12.w),
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.error,
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Icon(
                      Icons.delete,
                      color: Colors.white,
                      size: 24.sp,
                    ),
                  ),
                  onDismissed: (_) {
                    setState(() {
                      _viewModel.removeExpense(expense.id);
                    });
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text("Expense Removed"),
                        duration: Duration(seconds: 2),
                      ),
                    );
                  },
                  child: Card(
                    margin: EdgeInsets.only(bottom: 10.h),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12.r)),
                    elevation: 1,
                    child: ListTile(
                      leading: CircleAvatar(
                        backgroundColor: Theme.of(context)
                            .colorScheme
                            .primaryContainer
                            .withOpacity(0.3),
                        child: Icon(
                          expense.category == "Shopping"
                              ? Icons.shopping_bag
                              : expense.category == "Food & Drinks"
                                  ? Icons.fastfood
                                  : expense.category == "Transportation"
                                      ? Icons.directions_car
                                      : Icons.receipt,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                      ),
                      title: Text(
                        expense.title,
                        style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                              fontWeight: FontWeight.bold,
                            ),
                      ),
                      subtitle: Text(
                        DateFormat("MMM dd, yyyy").format(expense.date),
                        style: Theme.of(context).textTheme.bodySmall?.copyWith(
                              color: Theme.of(context)
                                  .colorScheme
                                  .onSurfaceVariant,
                            ),
                      ),
                      trailing: Text(
                        "-\$${expense.amount.toStringAsFixed(2)}",
                        style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                              fontSize: 12.sp,
                              color: Colors.redAccent,
                              fontWeight: FontWeight.bold,
                            ),
                      ),
                    ),
                  ),
                );
              },
            ),
    );
  }

  void _showBudgetDialog() {
    final budgetController =
        TextEditingController(text: _viewModel.budget.toString());

    showDialog(
      context: context,
      builder: (context) {
        return Center(
          child: SingleChildScrollView(
            child: AlertDialog(
              alignment: Alignment.center,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16.r),
              ),
              title: Text(
                "Update Budget",
                style: Theme.of(context).textTheme.titleLarge,
              ),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TextField(
                    controller: budgetController,
                    decoration: InputDecoration(
                      labelText: "Budget Amount",
                      prefixText: "\$",
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                    ),
                    keyboardType:
                        const TextInputType.numberWithOptions(decimal: true),
                  ),
                  SizedBox(height: 8.h),
                  Text(
                    "Current Budget: \$${_viewModel.budget.toString()}",
                    style: Theme.of(context).textTheme.bodySmall?.copyWith(
                          color: Theme.of(context).colorScheme.onSurfaceVariant,
                        ),
                  ),
                ],
              ),
              actionsPadding: EdgeInsets.symmetric(horizontal: 8.w),
              actions: [
                TextButton(
                  onPressed: () => RouteUtils.pop(context),
                  child: Text(
                    "Cancel",
                    style: TextStyle(fontSize: 14.sp),
                  ),
                ),
                FilledButton(
                  onPressed: () {
                    if (budgetController.text.isNotEmpty) {
                      setState(() {
                        _viewModel.setBudget(
                          double.tryParse(budgetController.text) ?? 0,
                        );
                      });
                      RouteUtils.pop(context);
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text("Budget updated successfully"),
                          duration: Duration(seconds: 2),
                        ),
                      );
                    }
                  },
                  child: Text(
                    "Update",
                    style: TextStyle(fontSize: 14.sp),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  void _showAddExpenseDialog() {
    final titleController = TextEditingController();
    final amountController = TextEditingController();
    String selectedCategory = "Shopping";

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Theme.of(context).colorScheme.surface,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16.r)),
      ),
      builder: (context) {
        return Padding(
          padding: EdgeInsets.only(
            bottom: MediaQuery.of(context).viewInsets.bottom,
            left: 16.w,
            right: 16.w,
            top: 16.h,
          ),
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Text(
                  "Add New Expense",
                  style: Theme.of(context).textTheme.titleLarge,
                  textAlign: TextAlign.center,
                ),
                SizedBox(height: 16.h),
                TextField(
                  controller: titleController,
                  decoration: InputDecoration(
                    labelText: "Title",
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                  ),
                ),
                SizedBox(height: 16.h),
                TextField(
                  controller: amountController,
                  decoration: InputDecoration(
                    labelText: "Amount",
                    prefixText: "\$",
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                  ),
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true),
                ),
                SizedBox(height: 16.h),
                DropdownButtonFormField<String>(
                  value: selectedCategory,
                  decoration: InputDecoration(
                    labelText: "Category",
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                  ),
                  items: [
                    "Shopping",
                    "Food & Drinks",
                    "Transportation",
                    "Bills"
                  ]
                      .map((category) => DropdownMenuItem(
                          value: category, child: Text(category)))
                      .toList(),
                  onChanged: (value) {
                    selectedCategory = value!;
                  },
                ),
                SizedBox(height: 20.h),
                FilledButton(
                  onPressed: () {
                    if (titleController.text.isNotEmpty &&
                        amountController.text.isNotEmpty) {
                      setState(() {
                        _viewModel.addExpense(
                          titleController.text,
                          double.tryParse(amountController.text) ?? 0,
                          selectedCategory,
                        );
                      });
                      RouteUtils.pop(context);
                    }
                  },
                  style: FilledButton.styleFrom(
                    padding: EdgeInsets.symmetric(vertical: 14.h),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                  ),
                  child: Text(
                    "Add Expense",
                    style: TextStyle(fontSize: 14.sp),
                  ),
                ),
                SizedBox(height: 20.h),
              ],
            ),
          ),
        );
      },
    );
  }
}
